package com.whut.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @ClassName:GlobalExceptionHandler
 * @Description:全局异常类
 * @Author:liumengying
 * @Date: 2022/7/25 10:10
 * Version v1.0
 */

//控制器横切注解，针对某个控制器类对象执行横切操作，这种全局处理方式，使用的面向切面编程

@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     * ExceptionHandeler注解表示该方法处理什么类型的异常
     * 指定了针对JDBC中的约束违反异常的处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Message<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            final String[] split=ex.getMessage().split(" ");
            String msg=split[2]+"已存在";
            return Message.error(msg);
        }
        return Message.error("未知错误");
    }

    /**
     * 业务异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public  Message<String> exceptionHandler(CustomException ex){
       log.error(ex.getMessage());
       return Message.error(ex.getMessage());
    }

    /**
     *
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public Message<String> exceptionHandler(FileSizeLimitExceededException ex){
        log.error("上传异常："+ex.getMessage());
        long fileSizeLimit = Long.parseLong(ex.getMessage().split(" ")[9])/1024/1024;
        return Message.error("上传文件不能大于"+fileSizeLimit+"MB");

    }

}
